package com.miku.blog.runner;

import com.miku.blog.domain.*;
import com.miku.blog.domain.dto.ResourceURIDTO;
import com.miku.blog.domain.pojo.SystemConstance;
import com.miku.blog.service.*;
import com.miku.blog.utils.DateUtils;
import com.miku.blog.utils.PathUtils;
import com.miku.blog.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author shkstart
 * @create ${}YEAR-06-12 23:02
 */
@Component
public class RedisRunner implements CommandLineRunner {

    @Autowired
    private RedisCache redisCache;
    @Autowired
    private CommentService commentService;
    @Autowired
    private ArticleService articleService;
    @Autowired
    private ResourceService resourceService;
    @Autowired
    private WebsiteService websiteService;

    @Override
    public void run(String... args) throws Exception {
        setResourceURIList();
        setRedisUniqueView();
        setRedisArticleViewCount();
        setRedisWebsiteConfigReview();
//        setRedisCommentsByType();
    }


    private void setResourceURIList(){

        List<Resource> resourceList = resourceService.getResourceChildrenList();
        Map<String, List<ResourceURIDTO>> map = new HashMap<>();
        for (Resource resource : resourceList) {
            //将 路径前缀作为键
            String url = resource.getUrl();
            String prefix = PathUtils.getPathPrefix(url);

            // 将同一路径前缀的接口映射存入一个集合
            if (map.containsKey(prefix)){
                List<ResourceURIDTO> list = map.get(prefix);
                list.add(new ResourceURIDTO(resource.getRequestMethod(),url,resource.getIsAnonymous()));
            }else {
                List<ResourceURIDTO> list = new ArrayList<>();
                list.add(new ResourceURIDTO(resource.getRequestMethod(),url,resource.getIsAnonymous()));
                map.put(prefix,list);
            }

        }

        Set<Map.Entry<String, List<ResourceURIDTO>>> entrySet = map.entrySet();
        for (Map.Entry<String, List<ResourceURIDTO>> entry : entrySet) {
            String key = entry.getKey();
            //将 请求映射 路径前缀作为 Hash键，将同一路径前缀的接口映射集合作为 值
            redisCache.setCacheHashMap(SystemConstance.RESOURCE_REQUEST_URI_LIST_KEY,
                                        key,
                                        entry.getValue());
        }

        setRedisExpireTime(SystemConstance.RESOURCE_REQUEST_URI_LIST_KEY);


    }


    private void setRedisUniqueView(){
        Date todayByZero = DateUtils.getDateByTodayMorning();
        String format = DateUtils.getSimpleDateFormatYMDHMS().format(todayByZero);
        redisCache.setCacheHashMap(SystemConstance.REDIS_UNIQUE_VIEW_KEY,
                format,
                SystemConstance.UNIQUE_VIEW_INIT);

        setRedisExpireTime(SystemConstance.REDIS_UNIQUE_VIEW_KEY);
    }

    private void setRedisArticleViewCount(){
        List<Article> articles = articleService.getAllArticleList();
        articles.stream()
                .peek(article -> {
                    redisCache.setCacheHashMap(SystemConstance.REDIS_ARTICLE_VIEW_COUNT_KEY,
                                                article.getId().toString(),
                                                article.getViewsCount());

                    setRedisExpireTime(SystemConstance.REDIS_ARTICLE_VIEW_COUNT_KEY);

                }).collect(Collectors.toList());

    }

    public void setRedisWebsiteConfigReview(){

        Website webSite = websiteService.getWebSite();
        redisCache.setCacheHashMap(SystemConstance.REDIS_WEBSITE_CONFIG_REVIEW_HASH_KEY,
                SystemConstance.REDIS_WEBSITE_IS_MESSAGE_REVIEW_KEY,
                webSite.getIsMessageReview());

        redisCache.setCacheHashMap(SystemConstance.REDIS_WEBSITE_CONFIG_REVIEW_HASH_KEY,
                SystemConstance.REDIS_WEBSITE_IS_COMMENT_REVIEW_KEY,
                webSite.getIsCommentReview());

        setRedisExpireTime(SystemConstance.REDIS_WEBSITE_CONFIG_REVIEW_HASH_KEY);

    }


//    private void setRedisCommentsByType(){
//        setRedisCommentsByType(SystemConstance.ARTICLE_TYPE_BY_ARTICLE_CODE,
//                                SystemConstance.REDIS_ARTICLE_COMMENT_CHILDREN_KEY);
//
//        setRedisCommentsByType(SystemConstance.ARTICLE_TYPE_BY_FRIEND_LINK_CODE,
//                                SystemConstance.REDIS_FRIEND_LINK_COMMENT_CHILDREN_KEY);
//
//        setRedisCommentsByType(SystemConstance.ARTICLE_TYPE_BY_TALK_CODE,
//                                SystemConstance.REDIS_TALK_COMMENT_CHILDREN_KEY);
//
//    }
//
//    private void setRedisCommentsByType(Integer type,String childrenKey){
//        List<Comment> rootComments = commentService.getAllRootCommentsByType(type);
//        rootComments.stream()
//                .peek(root -> {
//                    List<Comment> childrenComments = commentService.getAllChildrenCommentsByType(root.getId(),type);
//                    if (Objects.nonNull(childrenComments)){
//                        InsertSortUtils.insertSortByCommentCreateTimeUp(childrenComments);
//                    }else {
//                        childrenComments = new ArrayList<>();
//                    }
//
//                    setRedisCacheKey(childrenComments,
//                            root,
//                            childrenKey);
//
//                }).collect(Collectors.toList());
//    }
//
//
//
//    private void setRedisCacheKey(List<Comment> childrenComments,Comment root,String childrenKey){
//        String rootId = root.getId().toString();
//
//        redisCache.setCacheHashMap(childrenKey,
//                rootId,
//                childrenComments);
//
//        setRedisExpireTime(childrenKey);
//    }


    private void setRedisExpireTime(String hashKey){
        redisCache.setCacheObjectExpireTime(hashKey,
                SystemConstance.REDIS_CACHE_KEY_EXPIRE_TIME,
                SystemConstance.REDIS_TIMEUNIT);
    }

}
